﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using VictorBlaga.DocumentManagement.Core.Models.Repositories;
using VictorBlaga.DocumentManagement.Infrastructure;
using VictorBlaga.DocumentManagement.Models;

namespace VictorBlaga.DocumentManagement.Helpers.Validators.Impl
{
    public class WorkshopValidator : IWorkshopValidator
    {
        private WorkshopViewModel _viewModel;
        private List<ValidationError> _validationErrors;
        private readonly IWorkshopRepository _workshopRepository;

        public WorkshopValidator(IWorkshopRepository workshopRepository)
        {
            _validationErrors = new List<ValidationError>();
            this._workshopRepository = workshopRepository;
        }

        public WorkshopViewModel ViewModel
        {
            get { return _viewModel; }
            set
            {
                _viewModel = value;
                _validationErrors = new List<ValidationError>();
            }
        }

        public bool IsInsertValid()
        {
            return IsValid();
        }

        public ValidationError[] GetInsertValidationErrors()
        {
            return GetValidationErrors();
        }

        public bool IsUpdateValid()
        {
            return IsValid();
        }

        public ValidationError[] GetUpdateValidationErrors()
        {
            return GetValidationErrors();
        }

        private bool IsValid()
        {
            if (String.IsNullOrEmpty(_viewModel.Name))
                _validationErrors.Add(new ValidationError("Name must not be empty.", "Name"));
            else if (!_workshopRepository.IsUniqueName(_viewModel.Id, _viewModel.Name))
                _validationErrors.Add(new ValidationError("Name already exists. Chose another one.", "Name"));
            if (_viewModel.ManagerId == null)
                _validationErrors.Add(new ValidationError("You have to select a manager.", "ManagerId"));
            if (_viewModel.TeamId == null)
                _validationErrors.Add(new ValidationError("You have to select a team.", "TeamId"));

            return _validationErrors.Count == 0;
        }

        private ValidationError[] GetValidationErrors()
        {
            return _validationErrors.ToArray();
        }
    }
}
